﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI.WebControls;
using DNNspot.LiveChat.Common;
using DNNspot.LiveChat.DataModel;
using DotNetNuke.Common;
using DotNetNuke.Entities.Host;
using DotNetNuke.Entities.Users;

namespace DNNspot.LiveChat.Admin
{
    public partial class Default : ModuleBase
    {
        // ### EVENTS ######################################################

        protected void Page_PreRender(object sender, EventArgs e)
        {
            IncludeJS();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            HandlePostBack();
        }

        // ### PRIVATE FUNCTIONS ###########################################

        private void HandlePostBack()
        {
            var target = Request.Form["__EVENTTARGET"];
            var argument = Request.Form["__EVENTARGUMENT"];

            if (target == PostBackEvents.EditAgent)
            {
                var agentId = Convert.ToInt32(argument);
                Response.Redirect(Globals.NavigateURL(TabId, ControlKeys.EditAgent, new[] {
                    string.Format("mid={0}", ModuleId),
                    string.Format("{0}={1}", Params.AgentId, agentId)
                }));
            }
            else if (target == PostBackEvents.EditCategory)
            {
                var categoryId = Convert.ToInt32(argument);
                Response.Redirect(Globals.NavigateURL(TabId, ControlKeys.EditCategory, new[] {
                    string.Format("mid={0}", ModuleId),
                    string.Format("{0}={1}", Params.CategoryId, categoryId)
                }));
            }
            else if (target == PostBackEvents.EditSession)
            {
                var sessionId = Convert.ToInt32(argument);
                Response.Redirect(Globals.NavigateURL(TabId, ControlKeys.EditSession, new[] {
                    string.Format("mid={0}", ModuleId),
                    string.Format("{0}={1}", Params.SessionId, sessionId)
                }));
            }
        }

        private void IncludeJS()
        {
            if (string.IsNullOrEmpty(HostSettings.GetHostSetting(ModuleSettings.NoJQuery)) && HttpContext.Current.Items["jquery_registered"] == null)
            {
                RegisterJavascript(String.Format("{0}{1}js/jquery-1.3.1.min.js", Globals.ApplicationPath, ModuleWebPath));
                HttpContext.Current.Items.Add("jquery_registered", "true");
            }

            RegisterJavascript(string.Format("{0}{1}js/jquery.cookie.js", Globals.ApplicationPath, ModuleWebPath));
            RegisterJavascript(string.Format("{0}{1}js/jquery-ui-1.7.2.custom.min.js", Globals.ApplicationPath, ModuleWebPath));
            RegisterJavascript(string.Format("{0}{1}js/jquery.flexigrid.js", Globals.ApplicationPath, ModuleWebPath));
        }
    }
}

